<script setup>
import { computed, reactive, ref, toRaw } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import Type from '@components/search/type';
import Search from '@components/search/index';
import PageWrapper from '@components/PageWrapper.vue';
import { common, service } from '@utils';
import { Plus, Edit, Delete, View, Setting, TurnOff, Open, WarnTriangleFilled } from '@element-plus/icons-vue';
import { usePremission } from '@hooks';
import EditCom from './Edit';
import Detail from './Detail';
import Divide from './Divide';
import riskControlSet from './riskControlSet';
import { tryOnMounted } from '@vueuse/shared';
import store, { STORE_KEY } from '@store';

const premission = usePremission({
    view: 'merchant:company:detail', //详情
    add: 'merchant:company:save', //新增
    edit: 'merchant:company:edit', //编辑
    delete: 'sys:company:del', //删除
    // divide: 'sys:company:divide',
    saves: 'merchant:company:setProfitRates', //批量分成设置
    save: 'merchant:company:setProfitRate', //分成设置
    risks: 'merchant:company:setRiskRates', //批量风控设置
    risk: 'merchant:company:setRiskRate', //风控设置
    disable: 'merchant:company:disable', //禁用
    enable: 'merchant:company:enable', //启用
});
const searchs = ref([
    {
        type: Type.INPUT,
        key: 'label',
        width: 5,
        placeholder: '商户名称',
    },
    {
        type: Type.INPUT,
        key: 'contactName',
        width: 5,
        placeholder: '联系人',
    },
    {
        type: Type.INPUT,
        key: 'phone',
        width: 5,
        placeholder: '手机号',
    },
    {
        width: 6,
        type: Type.SEARCH_BUTTON,
    },
]);

const pageRef = ref();
const tableRef = ref();
const editRef = ref();
const detailRef = ref();
const divideRef = ref();
const riskControlSetRef = ref();
const rentTitleText = ref('');
const state = reactive({
    companyIds: [],
    labelNames: [],
    disabledRentDate: [],
});
const companyCode = computed(() => store.getters.user);

let queryForm = {
    code: companyCode.value.companyCode == 'platform' ? '' : companyCode.value.companyCode,
};

const onSearch = param => {
    queryForm = param;
    pageRef.value.refresh();
};

const getData = async ({ pageNum, pageSize }, cb) => {
    let res = await service.auth.companys(pageNum, pageSize, queryForm);
    let res2 = await service.bfqz.LeasePeriodSwitchList({});
    let resData = res2.sort((a, b) => {
        return a.id - b.id;
    });
    state.disabledRentDate = resData;
    state.companyIds = []
    let rentTitle = '';
    resData.forEach(item => {
        if (item.status != 0) {
            switch (item.day * 1) {
                case 30:
                    rentTitle += '单期/';
                    break;
                case 60:
                    rentTitle += '两期/';
                    break;
                case 90:
                    rentTitle += '三期/';
                    break;
                case 120:
                    rentTitle += '四期/';
                    break;
                case 150:
                    rentTitle += '五期/';
                    break;
                case 180:
                    rentTitle += '六期/';
                    break;
                case 210:
                    rentTitle += '七期/';
                    break;
                case 240:
                    rentTitle += '八期/';
                    break;
                case 270:
                    rentTitle += '九期/';
                    break;
                case 300:
                    rentTitle += '十期/';
                    break;
                case 330:
                    rentTitle += '十一期/';
                    break;
                default:
                    rentTitle += '十二期/';
                    break;
            }
        }
    });
    rentTitleText.value = rentTitle.substring(0, rentTitle.length - 1);

    res.list.forEach(jtem => {
        let rwoProfitRate = '';
        resData.forEach(item => {
            if (item.status != 0) {
                rwoProfitRate += `${jtem['profitRate' + item.day]}%/`;
                // switch (item.day * 1) {
                //     case 30:
                //         rwoProfitRate += `${jtem.firstProfitRate}%/`
                //         break
                //     case 60:
                //         rwoProfitRate += `${jtem.twoProfitRate}%/`
                //         break
                //     case 90:
                //         rwoProfitRate += `${jtem.threeProfitRate}%/`
                //         break
                //     case 120:
                //         rwoProfitRate += `${jtem.fourProfitRate}%/`
                //         break
                //     case 150:
                //         rwoProfitRate += `${jtem.fiveProfitRate}%/`
                //         break
                //     case 180:
                //         rwoProfitRate += `${jtem.sixProfitRate}%/`
                //         break
                //     case 210:
                //         rwoProfitRate += `${jtem.sevenProfitRate}%/`
                //         break
                //     case 240:
                //         rwoProfitRate += `${jtem.eightProfitRate}%/`
                //         break
                //     case 270:
                //         rwoProfitRate += `${jtem.nineProfitRate}%/`
                //         break
                //     case 300:
                //         rwoProfitRate += `${jtem.tenProfitRate}%/`
                //         break
                //     case 330:
                //         rwoProfitRate += `${jtem.elevenProfitRate}%/`
                //         break
                //     default:
                //         rwoProfitRate += `${jtem.twelveProfitRate}%/`
                //         break
                // }
            }
        });
        jtem.rwoProfitRate = rwoProfitRate.substring(0, rwoProfitRate.length - 1);
    });
    cb(res);
    setTimeout(() => {
        tableRef.value.scrollTo(0, 0);
    }, 0);
};
const selectAllChangeEvent1 = ({ checked, records }) => {
    getcompanyIds(records);
};

const selectChangeEvent1 = ({ checked, records }) => {
    getcompanyIds(records);
};
const getcompanyIds = records => {
    let companyIds = [];
    let labelNames = [];
    records.forEach(item => {
        companyIds.push(item.companyId);
        labelNames.push(item.label);
    });
    state.companyIds = companyIds;
    state.labelNames = labelNames;
};
const setcompanyIds = () => {
    if (state.companyIds.length > 0) {
        divideRef.value.open('批量分成', state.companyIds, state.disabledRentDate);
    } else {
        ElMessage.warning('请选择要修改的商户');
    }
};
const setRiskControl = () => {
    if (state.companyIds.length > 0) {
        riskControlSetRef.value.open('批量风控设置', state.companyIds, state.labelNames);
    } else {
        ElMessage.warning('请选择要修改的商户');
    }
};
const changeState = async (row, disabled) => {
    ElMessageBox.confirm(`是否${disabled ? '禁用' : '启动'}${row.label}`, '提示', {
        type: 'warning',
    }).then(async () => {
        let res;
        if (disabled) {
            res = await service.auth.companyDisable(row.companyId);
        } else {
            res = await service.auth.companyEnable(row.companyId);
        }

        if (res) {
            pageRef.value.refresh(true);
            ElMessage.success('修改成功');
        }
    });
};

const width = (function (premission) {
    let width = 24;
    premission.view && (width += 33);
    premission.edit && (width += 33);
    premission.delete && (width += 33);
    premission.enable && (width += 33);
    premission.disable && (width += 33);
    premission.save && (width += 33);
    premission.risk && (width += 33);
    return Math.max(width, 80);
})(premission);
</script>
<template>
    <section class="main-white">
        <search :items="searchs" @filter="onSearch" />
        <div :class="premission.add || premission.saves ? 'margin-bottom10' : ''" v-if="premission.add || premission.saves">
            <el-button type="primary" v-if="premission.add" :icon="Plus" @click="editRef.open({}, false, state.disabledRentDate)">添加</el-button>
            <el-button @click="setcompanyIds" v-if="premission.saves">批量分成设置</el-button>
            <el-button @click="setRiskControl" v-if="premission.risks">批量风控设置</el-button>
        </div>
        <page-wrapper @get-data="getData" ref="pageRef">
            <template v-slot:default="props">
                <vxe-table class="mytable-scrollbar" ref="tableRef" :loading="props.loading" :data="props.tableData.records" :max-height="common.tableHeight(true, premission.add ? 2 : 1)" @checkbox-all="selectAllChangeEvent1" @checkbox-change="selectChangeEvent1" highlight-hover-row align="center" round stripe border>
                    <vxe-column type="checkbox" width="60" fixed="left"></vxe-column>
                    <vxe-column type="seq" width="60"></vxe-column>
                    <vxe-column field="companyId" title="商户ID" width="150" />
                    <vxe-column field="label" title="商户名称" width="150" />
                    <vxe-column field="contactName" title="联系人" width="150" />
                    <!-- <vxe-column title="平台分成" width="100">
                        <template #default="{ row }">{{ row.profitRate }}%</template>
                    </vxe-column> -->
                    <vxe-column align="center" field="rwoProfitRate" :title="`租期${rentTitleText}平台分成`" width="300" />
                    <vxe-column align="center" title="风控视成报告/全景雷达/探针收费标准" width="250">
                        <template #default="{ row }">{{ row.seeRisk }}元 / {{ row.radarRisk }}元 / {{ row.probeRisk }}元</template>
                    </vxe-column>
                    <!-- <vxe-column title="租期三个月平台分成">
                        <template #default="{ row }">{{ row.platformThreeProfitRate }}%</template>
                    </vxe-column>
                    <vxe-column title="租期六个月平台分成">
                        <template #default="{ row }">{{ row.platformSixProfitRate }}%</template>
                    </vxe-column> -->
                    <vxe-column field="createTime" title="创建时间" width="170" />
                    <vxe-column field="createBy" title="创建人" width="100" />
                    <vxe-column title="操作" :min-width="width" fixed="right">
                        <template #default="{ row }">
                            <section class="flex-align flex-wrap">
                                <el-tooltip v-if="premission.view" effect="dark" content="详情" placement="top" :enterable="false">
                                    <el-button type="primary" plain :icon="View" size="small" circle @click="editRef.open(row, true, state.disabledRentDate)"></el-button>
                                </el-tooltip>
                                <el-tooltip v-if="premission.edit" effect="dark" content="修改" placement="top" :enterable="false">
                                    <el-button type="primary" :icon="Edit" size="small" circle @click="editRef.open(row, false, state.disabledRentDate)"></el-button>
                                </el-tooltip>
                                <el-tooltip v-if="premission.save" effect="dark" content="分成" placement="top" :enterable="false">
                                    <el-button
                                        type="success"
                                        :icon="Setting"
                                        size="small"
                                        circle
                                        @click="
                                            divideRef.open(
                                                '分成',
                                                {
                                                    ...row,
                                                    companyIds: [row.companyId],
                                                    // companyId: row.companyId,
                                                    // profitRate: row.profitRate,
                                                    // platformProfitRate: row.platformProfitRate,
                                                    // firstProfitRate: row.firstProfitRate,
                                                    // twoProfitRate: row.twoProfitRate,
                                                    // threeProfitRate: row.threeProfitRate,
                                                    // fourProfitRate: row.fourProfitRate,
                                                    // fiveProfitRate: row.fiveProfitRate,
                                                    // sixProfitRate: row.sixProfitRate,
                                                    // sevenProfitRate: row.sevenProfitRate,
                                                    // eightProfitRate: row.eightProfitRate,
                                                    // nineProfitRate: row.nineProfitRate,
                                                    // tenProfitRate: row.tenProfitRate,
                                                    // elevenProfitRate: row.elevenProfitRate,
                                                    // twelveProfitRate: row.twelveProfitRate
                                                },
                                                state.disabledRentDate,
                                                rentTitleText
                                            )
                                        "
                                    ></el-button>
                                </el-tooltip>
                                <el-tooltip v-if="premission.risk" effect="dark" content="风控设置" placement="top" :enterable="false">
                                    <el-button
                                        type="warning"
                                        :icon="WarnTriangleFilled"
                                        size="small"
                                        circle
                                        @click="
                                            riskControlSetRef.open('风控设置', {
                                                companyIds: [row.companyId],
                                                label: row.label,
                                                seeRisk: row.seeRisk,
                                                radarRisk: row.radarRisk,
                                                probeRisk: row.probeRisk,
                                            })
                                        "
                                    ></el-button>
                                </el-tooltip>
                                <el-tooltip v-if="premission.disable && row.status" effect="dark" content="禁用" placement="top" :enterable="false">
                                    <el-button type="danger" :icon="TurnOff" size="small" circle @click="changeState(row, true)"></el-button>
                                </el-tooltip>
                                <el-tooltip v-if="premission.enable && !row.status" effect="dark" content="启用" placement="top" :enterable="false">
                                    <el-button type="success" :icon="Open" size="small" circle @click="changeState(row, false)"></el-button>
                                </el-tooltip>
                            </section>
                        </template>
                    </vxe-column>
                </vxe-table>
            </template>
        </page-wrapper>
        <edit-com ref="editRef" @refresh="flag => pageRef.refresh(flag)" />
        <detail ref="detailRef" />
        <divide ref="divideRef" @refresh="() => pageRef.refresh(true)" />
        <riskControlSet ref="riskControlSetRef" @refresh="() => pageRef.refresh(true)" />
    </section>
</template>
